# -*- coding: utf-8 -*-
import socket
from urllib import request, parse, error
import gzip
import io

URL = 'https://www.python.org'
httpbin = 'https://www.httpbin.org/post'


def get_html(url=URL, header=True):
    response = request.urlopen(url)

    if header:
        print(type(response))
        print(response.status)
        print(response.getheaders())
        print(response.getheader('Server'))
    else:
        # 检查 Content-Encoding 头部信息
        encoding = response.headers.get('Content-Encoding')

        if encoding == 'gzip':
            # 对 gzip 压缩的内容进行解压缩
            content = gzip.GzipFile(fileobj=io.BytesIO(response.read())).read()
        else:
            # 直接读取响应内容
            content = response.read()
        # 尝试使用 utf-8 解码
        print(content.decode('utf-8'))


def urlopen_with_data(url=httpbin):
    data = bytes(parse.urlencode({'word': 'hello', 'name': 'vincent'}), encoding='utf8')
    response = request.urlopen(url, data=data)
    print(response.read().decode('utf-8'))


def urlopen_with_timeout(url=httpbin):
    try:
        response = request.urlopen(url, timeout=0.1)
    except error.URLError as e:
        if isinstance(e.reason, socket.timeout):
            print('Time Out')


def request_demo(url=URL):
    req = request.Request(url)
    req.add_header('User-Agent',
                   'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
    response = request.urlopen(req)
    encoding = response.headers.get('Content-Encoding')
    if encoding == 'gzip':
        # 对 gzip 压缩的内容进行解压缩
        content = gzip.GzipFile(fileobj=io.BytesIO(response.read())).read()
    else:
        # 直接读取响应内容
        content = response.read()
    print(content.decode('utf-8'))


def requst_post(url=httpbin):
    headers = {
        'User-Agent': 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25',
        'Host': 'www.httpbin.org'
    }

    _dict = {'name': 'vincent'}
    data = bytes(parse.urlencode(_dict), encoding='utf-8')
    req = request.Request(url=url, data=data, headers=headers, method='POST')
    response = request.urlopen(req)
    print(response.read().decode('utf-8'))


if __name__ == '__main__':
    # get_html()
    # urlopen_with_data()
    # urlopen_with_timeout()
    # request_demo()
    requst_post()
